<template>
	<ls-skeleton :loading="loading">
		<view class="container">
			<view class="uni-list a">
				<view class="uni-list-cell uni-list-cell-pd" @click="getAddress">
					<image mode="widthFix" src="../../../static/images/pro_12.png" class="pic"></image>
					<view class="uni-list-cell-db" v-if="addressId > 0">
						<view class="h3">{{addressInfo.receiveName}} {{addressInfo.receivePhone}}</view>
						<view v-if="addressInfo.address">
							{{addressInfo.provinceName + '/' + addressInfo.cityName + '/' + addressInfo.districtName + ' ' + addressInfo.address}}
						</view>
					</view>
					<view v-else class="uni-list-cell-db">设置收货地址</view>
					<view class="uni-navigate-right"></view>
				</view>
			</view>
			<view class="uni-list b">
				<view class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in list" :key="index">
					<image mode="widthFix" :src="item.productImage" class="pic"></image>
					<view class="uni-list-cell-db">
						<view class="h3">{{item.productName}}</view>
						<view class="h4">{{item.specifications}}</view>
						<view class="p uni-flex">
							<!-- 2024-01-21 -->
							<!-- <view class="uni-flex-item" v-if="userType == 'STORE'">￥{{item.productPrice}}</view> -->
							<!-- 							<view class='money' v-if="item.proxyPrice && userType == 'STORE'">
								￥{{item.proxyPrice || item.salePrice}}</view>
							<view class='money' v-else-if="item.productPrice && userType == 'SALE'">
								￥{{item.productPrice || item.salePrice}}</view>
							<view class='money' v-else>￥{{item.salePrice || 0}}</view> -->

							<view class="uni-flex-item" v-if="item.proxyPrice && userType == 'STORE'">
								￥{{item.proxyPrice||item.salePrice}}</view>
							<view class="uni-flex-item" v-else-if="item.productPrice && userType == 'SALE'">
								￥{{item.productPrice||item.salePrice}}</view>
							<view class="uni-flex-item" v-else>￥{{item.salePrice||0}}</view>
							<view>×{{item.buyNumber}}</view>
						</view>
					</view>
				</view>
				<view class="uni-list-cell uni-list-cell-pd">
					<view class="uni-list-cell-db">
						<view class="uni-inline-item" v-if="isYunFei">
							<view class="uni-flex-item">运费：</view>
							<view>{{ freight_limit < totalPrice ? 0 : freight_fee }}</view>
						</view>
						<view class="uni-inline-item">
							<view class="uni-flex-item">数量：</view>
							<view>{{totaNum}}</view>
						</view>

						<view class="uni-flex">
							<view class="uni-flex-item">总价：</view>
							<text>￥{{totalPrice}}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="uni-inline-item"
				style="display: flex;justify-content: center; align-items: center; color: #999999;">
				<text>金额超过500元免运费</text>
			</view>
			<view class="footer">
				<u-button type="primary" color="#06A972" text="立即支付" :disabled="disabled"
					@click="createOrder"></u-button>
			</view>
		</view>
	</ls-skeleton>
</template>


<script>
	import {
		toLogin,
	} from '@/libs/login.js';
	import {
		amountPay,
		getUserCarSel,
		submitInCar,
		paySuccessPrint,
		xcxPay
	} from "@/api/order.js";
	import {
		getAddress,
		getDefault
	} from '@/api/userAddr.js';
	import {
		getParam
	} from '@/api/common.js';
	import {
		HEADER,
		HTTP_REQUEST_URL,
	} from '@/config/app';
	import {
		getUserAmount,
		getUserInfo
	} from '@/api/user.js';
	import {
		mapGetters
	} from "vuex";
	export default {
		data() {
			return {
				addressInfo: {},
				addressId: 0,
				address: {
					receiveName: '选择收货地址',
					receivePhone: '',
					address: '',
					addressId: 0,
				},
				totalPrice: 0,
				totaNum: 0,
				disabled: false,
				cartIds: "",
				list: [],
				is_balance: true,
				userAmount: {},
				freight_limit: 0,
				freight_fee: 0,
				loading: true,
				not_yunfeiList: [],
				isYunFei: true
			}
		},
		computed: mapGetters(['isLogin', 'uid', 'userType']),
		async onLoad(option) {
			const that = this;
			if (that.isLogin == false) {
				toLogin();
			}
			// 运费
			that.freight_limit = await that.getParam('XCX_FREIGHT_LIMIT');
			that.freight_fee = await that.getParam('XCX_FREIGHT_FEE');
			// 获取用户余额
			that.getUserAmount();

			//获取不需要运费的批发商
			let notYunFeiListStr = await that.getParam('XCX_NO_YUNFEI');

			// 将字符串解析为数组
			  try {
			    that.not_yunfeiList = JSON.parse(notYunFeiListStr);
			  } catch (error) {
			    console.error('解析 not_yunfeiList 时出错:', error);
			    that.not_yunfeiList = []; // 如果解析失败，设置为空数组
			  }

			await getUserInfo({
				userInfoId: that.uid,
			}).then(res => {
				if (res.value.frontUserPhone) {
					that.not_yunfeiList.forEach(item => { 
						if (`${item}` === `${res.value.frontUserPhone}`) {
							that.isYunFei = false;  
						}
					})
				} 
			})
			

			// that.cartIds = option.cartId.split(",");
			that.cartIds = option.cartId;
			that.getOrderDetail();


		},

		onShow() {
			let that = this;
			// uni.$on('addressId', function(addressId) {
			// 	that.address.addressId = addressId
			// })
			// that.getaddressInfo();
			uni.$on('addressId', function(addressId) {
				that.addressId = addressId
			})
			that.getaddressInfo();
		},

		methods: {
			/**
			 * 获取订单信息
			 */
			getOrderDetail() {
				let that = this;
				getUserCarSel({
					userInfoId: that.$store.state.app.uid,
					carIdArrStr: that.cartIds
				}).then(res => {
					that.loading = false;
					let countPrice = 0.00,
						countNum = 0;
					that.list = res.value;
					that.list.forEach((e) => {
						if (that.userType == 'STORE') {
							// 2024-01-21
							// countPrice = that.$util.$h.Add(countPrice, that.$util.$h.Mul(e.buyNumber, e
							// 	.productPrice || 0));
							countPrice = that.$util.$h.Add(countPrice, that.$util.$h.Mul(e.buyNumber, e
								.proxyPrice || e.salePrice));
						} else if (that.userType == 'SALE') {
							countPrice = that.$util.$h.Add(countPrice, that.$util.$h.Mul(e.buyNumber, e
								.productPrice || e.salePrice));
						} else {
							countPrice = that.$util.$h.Add(countPrice, that.$util.$h.Mul(e.buyNumber, e
								.salePrice || 0));
						}
						countNum = that.$util.$h.Add(countNum, e.buyNumber);
					});
					if (that.isYunFei) {
						// 运费
						if (countPrice < that.freight_limit) {
							countPrice = that.$util.$h.Add(countPrice, that.freight_fee);
						}
					}
					that.totalPrice = countPrice;
					that.totaNum = countNum;
				}).catch(err => {
					that.$util.Tips({
						title: err.msg
					});
				})

			},

			/**
			 * 创建订单
			 */
			async createOrder() {
				let that = this;
				that.disabled = true;
				let orderId = 0;

				if (that.addressId == 0) {
					that.disabled = false;
					return that.$util.Tips({
						title: '请选择收货地址',
					});
				}

				// #ifdef MP
				// if (that.is_balance) {
				// 	if (that.userAmount.totalPrice < that.totalPrice) {
				// 		return that.$util.Tips({
				// 			title: '余额不足，请前去充值',
				// 		}, {
				// 			tab: 5,
				// 			url: '/pages/users/user_payment/index'
				// 		});
				// 	} else {
				// 		uni.showModal({
				// 			title: "余额支付",
				// 			content: `您本次需要支付${that.totalPrice}`,
				// 			success: (async res => {
				// 				if (res.confirm) {
				// 					uni.showLoading({
				// 						title: '订单支付中'
				// 					});
				// 					// 创建订单
				// 					orderId = await that.submitInCar();
				// 					// 余额支付
				// 					that.amountPay(orderId);
				// 				} else {
				// 					that.disabled = false;
				// 				}
				// 			})
				// 		})
				// 	}
				// } else {
				uni.showLoading({
					title: '订单支付中'
				});
				orderId = await that.submitInCar();
				// 微信支付
				that.payment(orderId);
				// }
				// #endif
			},

			/**
			 * 创建订单
			 */
			submitInCar() {
				let that = this;
				return new Promise((resolve, reject) => {
					submitInCar({
						carIdArrStr: that.cartIds,
						userInfoId: that.uid,
						addressId: that.addressId
					}).then(res => {
						resolve(res.value);
					}).catch(err => {
						reject(err)
					});
				})
			},

			// createOrder1() {
			// 	let that = this;
			// 	that.disabled = true;
			// 	if (that.address.addressId == 0) {
			// 		return that.$util.Tips({
			// 			title: '请选择收货地址'
			// 		});
			// 	}
			// 	submitInCar({
			// 		carIdArrStr: that.cartIds,
			// 		userInfoId: that.$store.state.app.uid,
			// 		addressId: that.address.addressId
			// 	}).then(res => {
			// 		// #ifdef MP
			// 		if (that.is_balance) {
			// 			// 余额支付
			// 			if (!(that.userAmount.totalPrice < that.totalPrice)) {
			// 				uni.hideLoading();
			// 				return that.$util.Tips({
			// 					title: '余额不足，请前去充值',
			// 				}, {
			// 					tab: 5,
			// 					url: '/pages/users/user_payment/index'
			// 				});
			// 			} else {
			// 				uni.showModal({
			// 					title: "余额支付",
			// 					content: `您本次需要支付${that.totalPrice}`,
			// 					success(res) {
			// 						if (res.confirm) {
			// 							uni.showLoading({
			// 								title: '订单支付中'
			// 							});
			// 							that.amountPay(res.value);
			// 						} else {
			// 							that.disabled = false;
			// 						}
			// 					}
			// 				})
			// 			}
			// 		} else {
			// 			uni.showLoading({
			// 				title: '订单支付中'
			// 			});
			// 			// 微信支付
			// 			that.payment(res.value);
			// 		}
			// 		// #endif
			// 	}).catch(err => {
			// 		that.$util.Tips({
			// 			title: err.msg
			// 		});
			// 	})
			// },

			/**
			 * 余额支付
			 * @param {Object} orderId
			 */
			amountPay(orderId) {
				console.log("3：" + orderId);

				let that = this;
				amountPay({
					userInfoId: that.uid,
					orderId: orderId
				}).then(res => {
					uni.hideLoading();
					let goPages = '/pages/users/order_list/index?type=';
					// goPages += '?orderId=' + orderId;
					return that.$util.Tips({
						title: '支付成功',
						icon: 'success'
					}, {
						tab: 5,
						url: goPages + '&WAIT_SEND'
					});
				}).catch(err => {
					console.log("4：" + err);
					uni.hideLoading();
					that.$util.Tips({
						title: err
					});
				})
			},

			/**
			 * 支付
			 * @param {Object} orderId
			 */
			payment(orderId) {
				console.log("1：" + orderId);
				let that = this;
				xcxPay({
					orderId: orderId,
					userInfoId: that.$store.state.app.uid,
				}).then(res => {
					let goPages = '/pages/users/order_list/index?type=';
					// goPages += '?orderId=' + orderId;
					let jsConfig = res.value.param;
					console.log("2：" + res.value.param)
					// #ifdef MP
					uni.requestPayment({
						timeStamp: jsConfig.timeStamp,
						nonceStr: jsConfig.nonceStr,
						package: jsConfig.package,
						signType: jsConfig.signType,
						paySign: jsConfig.paySign,
						success: function(res) {
							uni.hideLoading();
							paySuccessPrint({
								orderId: orderId,
							}).then(res => {

							})
							return that.$util.Tips({
								title: '支付成功',
								icon: 'success'
							}, {
								tab: 5,
								url: goPages + "WAIT_SEND"
							});
						},
						fail: function(e) {
							console.log("取消支付");
							// 调用后端接口，更新订单状态为待支付
							uni.request({
								url: HTTP_REQUEST_URL + '/api/order/cancelPayment',
								// url: HTTP_REQUEST_URL + '/order/cancelPayment',
								method: 'POST',
								data: {
									orderId: orderId
								},
								success: () => {
									console.log('订单状态更新为待支付');
								},
							});
							uni.hideLoading();
							return that.$util.Tips({
								title: '取消支付'
							}, {
								tab: 5,
								url: goPages + 'WAIT_PAY'
							});
						},
						complete: function(e) {
							uni.hideLoading();
							//关闭当前页面跳转至订单状态
							if (res.errMsg == 'requestPayment:cancel') {
								return that.$util
									.Tips({
										title: '取消支付'
									}, {
										tab: 5,
										url: goPages + 'WAIT_PAY'
									});
							}
						},
					})
					// #endif
				}).catch(err => {
					that.$util.Tips({
						title: err.msg
					});
				})
			},

			/**
			 * 选择地址
			 */
			getAddress() {
				this.$util.Tips('/pages/goods/address/index');
			},

			/*
			 * 获取默认收货地址或者获取某条地址信息
			 */
			getaddressInfo() {
				let that = this;
				if (that.addressId) {
					getAddress({
						userInfoId: that.uid,
						addressId: that.addressId
					}).then(res => {
						that.loading = false;
						that.addressInfo = res.value || {};
						that.addressId = that.addressInfo.addressId ? res.value.addressId || 0 : 0;
					}).catch(err => {
						that.$util.Tips({
							title: err
						})
					})
				} else {
					getDefault({
						userInfoId: that.uid
					}).then(res => {
						that.loading = false;
						that.addressInfo = res.value || {};
						that.addressId = res.value.addressId || 0;
					}).catch(err => {
						that.$util.Tips({
							title: err
						})
					})
				}
			},

			/**
			 * 获取余额
			 */
			getUserAmount() {
				let that = this;
				getUserAmount({
					userInfoId: that.uid
				}).then(res => {
					that.userAmount = res.value;
				})
			},

			/**
			 * 获取参数
			 * @param {Object} paramType
			 */
			getParam(paramType) {
				return new Promise((resolve, reject) => {
					getParam({
						paramType: paramType
					}).then(res => {
						resolve(res.value);
					}).catch(err => {
						reject(err);
					})
				});
			},
		}
	}
</script>

<style>
	page {
		background: #F3F3F3;
	}

	.container {
		padding: 20rpx;
	}

	.container .uni-list {
		border-radius: 20rpx;
		margin-bottom: 20rpx;
	}

	.container .a image {
		width: 21rpx;
		height: 25rpx;
		margin-right: 30rpx;
	}

	.container .a .h3 {
		font-weight: bold;
	}

	.container .a .h3 text {
		padding-left: 30rpx;
	}

	.container .b .pic {
		width: 148rpx;
		height: 168rpx;
		margin-right: 20rpx;
	}

	.container .b .h3 {
		line-height: 40rpx;
		font-weight: bold;
	}

	.container .b .h4 {
		font-size: 24rpx;
		color: #868686;
		margin-top: 3px;
	}

	.container .b .p .uni-flex-item {
		font-size: 32rpx;
		font-weight: bold;
		color: #E91E1E;
	}

	.container .b .uni-inline-item {
		color: #BDBDBD;
	}

	.container .b .uni-flex text {
		font-size: 32rpx;
		font-weight: bold;
	}




	.bottom {
		font-size: 24rpx;
		line-height: 36rpx;
		position: fixed;
		z-index: 99;
		left: 0;
		bottom: 0;
		padding: 10rpx 30rpx;
		background-color: #fff;
		box-sizing: border-box;
		width: 100%;
	}
</style>